<template>
  <div>
    <el-drawer :title="$t('message.fbpk')" :visible.sync="isShowModal" :before-close="modalClose" size="1000px">
      <QueryForm v-model="filters" :query-form-config="queryFormConfig" @handleQuery="getList(1)" @clear="clearList">
        <template #btns>
          <el-button v-if="meta.indexOf('exportCourseClassList') > -1" :loading="exportLoading" type="primary" @click="handleExport">{{ $t('message.daochu') }}</el-button>
        </template>
      </QueryForm>
      <div v-if="meta.indexOf('AddAndUpdateClass') > -1" class="doumee_table_header">
        <el-button type="primary" @click="showClassAdd()">{{ $t('message.xzbj') }}</el-button>
      </div>

      <el-table ref="table" v-loading="listLoading" :data="list" element-loading-text="Loading" border fit :header-row-class-name="'table-header'" class="doumee-element-table doumee-element-tableb">
        <el-table-column align="center" :label="$t('message.bjmc')" min-width="120" prop="name" show-overflow-tooltip />
        <!-- <el-table-column
        align="center"
        :label="$t('message.keshi')"
        prop="classNum"
        min-width="100"
      /> -->
        <el-table-column align="center" :label="$t('message.skjl')" prop="teacherName" min-width="100" show-overflow-tooltip />
        <el-table-column align="center" :label="$t('message.bjzrs')" prop="studentNum" show-overflow-tooltip min-width="100" />
        <el-table-column align="center" :label="$t('message.yfpxys')" prop="allocatedNum" min-width="120" show-overflow-tooltip />
        <el-table-column align="center" :label="$t('message.skdd')" prop="site" min-width="100" show-overflow-tooltip />
        <el-table-column align="center" :label="$t('message.pkzt')" prop="timeStatus" :min-width="$i18n.locale === 'ZH'? 80 : 120" fixed="right">
          <template slot-scope="scope">
            <span class="studentNum">{{
              scope.row.timeStatus == "0" ? $t('message.wpk') : $t('message.ypk')
            }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('message.caozuo')" :width="$i18n.locale === 'ZH'? 220 : 410" align="center" fixed="right">
          <template slot-scope="scope">
            <div class="flex-cc">
              <el-button v-if="meta.indexOf('exportCourseClassList') > -1" type="text" @click="showClassAdd(scope.row)">{{ $t('message.edit') }}</el-button>
              <el-button v-if="meta.indexOf('StudentsInClass') > -1" type="text" @click="allotRowClick(scope.row)">{{ $t('message.fpxy') }}</el-button>
              <el-button v-if="meta.indexOf('CourseClassList') > -1" type="text" @click="schedulRowClick(scope.row)">{{ $t('message.pk') }}</el-button>
              <el-button v-if="meta.indexOf('DelCourseClass') > -1" type="text" @click="rowDel(scope.row)">{{ $t('message.del') }}</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <Paginations :total="total" :page="pagination.page" @current-change="getList" @SizeChange="handleSizeChange" />
    </el-drawer>
    <el-dialog ref="drawerClassRef" :title="classForm.id?$t('message.bjbj'):$t('message.xzbj')" :visible.sync="isShowClassDrawer" :before-close="closeClassDrawer" width="560px">
      <el-form ref="classFormRef" :model="classForm" :rules="rules" label-suffix="：" label-width="auto" class="demo-ruleForm">
        <el-form-item :label="$t('message.bjmc')" prop="name">
          <el-input v-model="classForm.name" />
        </el-form-item>
        <el-form-item :label="$t('message.bjrs')">
          <el-input v-model="classForm.studentNum" />
        </el-form-item>
        <el-form-item :label="$t('message.skjl')">
          <el-select v-model="classForm.teacherId" style="width: 100%;" :placeholder="$t('message.qxz') + $t('message.skjl')">
            <el-option v-for="item in teachers" :key="item.teacherId" :label="item.teacherName" :value="item.teacherId" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="isShowClassDrawer = false">{{ $t('message.qx') }}</el-button>
          <el-button v-preventReClick :loading="subLoading" type="primary" @click="subClassChange">{{ $t('message.qr') }}</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog :title="$t('message.tjxy')" :visible.sync="apporDialog" width="850px" :before-close="appormodalClose">
      <div>
        <div class="classInfo df mb20">
          <div class="flex1">{{ $t('message.kcmc') }}：{{ courseName }}</div>
          <div class="flex1">{{ $t('message.bjmc') }}：{{ classTemp.name }}</div>
          <div class="flex1">{{ $t('message.jiaolian') }}：{{ classTemp.teacherName }}</div>
        </div>
        <el-transfer v-model="selStudents" filterable class="transfer-class" :filter-placeholder="$t('message.search')" :titles="[$t('message.dtjxylb'), $t('message.ytjxylb')]" :data="studentList" :props="{
            key: 'id',
            label: 'name'
          }" />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="apporDialog = false">{{ $t('message.qx') }}</el-button>
        <el-button type="primary" @click="allocStudents">{{ $t('message.qd') }}</el-button>
      </span>
    </el-dialog>
    <ScheduleCard v-if="isShowScheduleCard" ref="ScheduleCardRef" @close="ScheduleCard" />
  </div>
</template>

<script>
import QueryForm from '@/components/QueryForm'
import { queryFormConfig } from './config'
import {
  getCourseClassList,
  UpdateCourseClass,
  delCourseClass,
  courseStudentListPost,
  allocStudentsPost,
  teacherList,
  courseClassEx
} from '@/api'
import ScheduleCard from '@/views/offlinecourses/scheduleCard'
export default {
  components: {
    QueryForm,
    ScheduleCard
  },
  props: {
    meta: {
      type: Array,
      default: () => []
    }
  },
  data () {
    return {
      isShowScheduleCard: false,
      isShowModal: false,
      exportLoading: false,
      courseId: '',
      courseName: '',
      site: '',
      teacherId: '',
      queryFormConfig,
      filters: {},
      total: 0,
      list: [],
      classTemp: {},
      teachers: [],
      listLoading: false,
      pagination: {
        page: 1,
        rows: 10
      },
      subLoading: false,

      isShowClassDrawer: false,
      classForm: {},
      modalDialog: this.$store.getters.dialog,
      rules: {
        name: [
          { required: true, message: this.$t('message.qsc') + this.$t('message.bjmc'), trigger: 'blur' }
        ]
      },

      apporDialog: false,
      studentList: [],
      selStudents: []

    }
  },
  mounted () {
    this.getTeachList()
  },
  methods: {
    showClassAdd (row) {
      if (row && row.id) {
        this.classForm = row
      } else {
        this.classForm = {
          teacherId: this.teacherId
        }
      }
      this.isShowClassDrawer = true
    },
    ScheduleCard () {
      this.isShowScheduleCard = false
      this.getList()
    },
    handleExport () {
      const { filters } = this
      this.exportLoading = true
      courseClassEx({
        param: {
          ...filters,
          courseId: this.courseId,
          venueId: sessionStorage.getItem('venueId')
        }
      })
        .then((res) => {
          this.exportLoading = false
          if (res.errorCode === '000000') {
            const a = document.createElement('a') // 创建一个a标签元素
            a.style.display = 'none' // 设置元素不可见
            a.href = res.record.showUrl // 设置下载地址
            document.body.appendChild(a) // 加入
            a.click() // 触发点击,下载
            document.body.removeChild(a) //
            this.$message.success(this.$t('message.dccg'))
          }
        })
        .catch(() => {
          this.exportLoading = false
        })
    },
    allocStudents () {
      const { selStudents, classTemp } = this
      allocStudentsPost({
        param: {
          classId: classTemp.id,
          studentList: selStudents
        }
      }).then(res => {
        if (res.errorCode !== '000000') return
        this.apporDialog = false
        this.$message.success(this.$t('message.fpcg'))
        this.getList()
      })
    },
    subClassChange () {
      this.$refs['classFormRef'].validate((valid) => {
        if (valid) {
          this.subLoading = true
          UpdateCourseClass({
            param: {
              ...this.classForm,
              courseId: this.courseId
            }
          }).then(res => {
            this.subLoading = false
            this.isShowClassDrawer = false
            this.getList(this.pagination.page)
          }, () => {
            this.subLoading = false
          })
        }
      })
    },
    getTeachList (page) {
      const venueId = sessionStorage.getItem('venueId')
      teacherList({ param: { venueId, teacherType: '0', status: '1', isOnJob: '1' } })
        .then(res => {
          this.teachers = res.recordList
          this.queryFormConfig.formItems[1].options = res.recordList.map(item => {
            item.value = item.teacherId
            item.label = item.teacherName
            return item
          })
        })
    },
    getList (page) {
      const { filters, pagination } = this
      const venueId = sessionStorage.getItem('venueId')
      if (page) {
        pagination.page = page
      }
      this.pagination = pagination
      this.listLoading = true
      getCourseClassList({ pagination, param: { venueId, ...filters, courseId: this.courseId } })
        .then(res => {
          this.listLoading = false
          if (res.errorCode === '000000') {
            this.list = res.recordList
            this.total = res.totalCount
          }
        }).catch(() => {
          this.listLoading = false
        })
    },
    rowDel (row) {
      this.$confirm(this.$t('message.scbjtc'), this.$t('message.ts'), {
        type: 'warning'
      }).then(() => {
        delCourseClass({
          param: {
            id: row.id
          }
        }).then(res => {
          if (res.errorCode !== '000000') return
          this.$message.success(this.$t('message.delcg'))
          let totalPage = Math.ceil((this.total - 1) / this.pagination.rows)
          let currentPage = this.pagination.page > totalPage ? totalPage : this.pagination.page
          this.pagination.page = currentPage < 1 ? 1 : currentPage
          this.getList(this.pagination.page)
        })
      })
    },
    clearList () {
      this.filters = {}
      this.getList(1)
    },
    allotRowClick (row) {
      this.apporDialog = true
      this.classTemp = { ...row }
      this.courseStudent(row.id)
    },
    schedulRowClick (row) {
      this.isShowScheduleCard = true
      this.$nextTick(() => {
        this.$refs.ScheduleCardRef.isShowDrawer = true
        this.$refs.ScheduleCardRef.courseId = this.courseId
        this.$refs.ScheduleCardRef.teacherId = row.teacherId
        this.$refs.ScheduleCardRef.site = this.site
        this.$refs.ScheduleCardRef.classId = row.id
        this.$refs.ScheduleCardRef.getList()
      })
    },
    courseStudent (id) {
      courseStudentListPost({
        param: {
          courseId: this.courseId,
          classId: id
        }
      }).then(res => {
        this.studentList = res.recordList || []
        this.selStudents = this.studentList.filter(i => i.flag === '2').map(i => i.id)
        console.log(this.selStudents)
      })
    },
    closeClassDrawer () {
      this.isShowClassDrawer = false
    },
    modalClose () {
      this.isShowModal = false
      this.$emit('close')
    },
    handleSizeChange (val) {
      this.pagination.rows = val
      this.getList(1)
    },
    appormodalClose () {
      this.apporDialog = false
    }

  }
}
</script>

<style lang="scss">
.transfer-class .el-transfer-panel {
  width: 300px !important;
}
</style>
